using System;
using System.Web;
using System.Web.Caching;
using IFXplus.SmartStorage.Settings;

namespace IFXplus.SmartStorage.Providers
{
    internal class AspNetCacheStorageProvider : IStorageProvider
    {
        #region Privates

        private readonly StorageProviderReference _reference = null;
        private readonly AspNetCacheStorageProviderSettings _settings = null;

        #endregion
        
        #region Constructor

        public AspNetCacheStorageProvider(StorageProviderReference reference)
        {
            if (reference == null)
                throw new ArgumentNullException("reference");
            if (string.IsNullOrEmpty(reference.Id))
                throw new ArgumentException("reference.Id cannot be null or empty", "reference");
            _reference = reference;
            _settings = StorageSettings.GetInstance().GetStorageProviderSettings<AspNetCacheStorageProviderSettings>(reference.Id);
            if (_settings == null)
                throw new StorageSettingsException(string.Format("{0} provider settings not found", reference));
        }

        #endregion

        #region Properties

        private AspNetCacheStorageProviderSettings Settings
        {
            get { return _settings; }
        }

        #endregion

        #region IStorageProvider Members

        public StorageProviderReference Reference
        {
            get { return _reference; }
        }

        public void Insert(StorageEntry entry)
        {
            try
			{
                HttpRuntime.Cache.Insert(entry.Key, entry, null, Cache.NoAbsoluteExpiration, Settings.SlidingExpiration, Settings.Priority, null);
			}
			catch (Exception ex)
			{
                throw new StorageException(string.Format("Exception in AspNetCacheStorageProvider.Insert({0})", entry), ex);
			}
        }

        public void Remove(string key)
        {
            try
            {
                HttpRuntime.Cache.Remove(key);
            }
            catch (Exception ex)
            {
                throw new StorageException(string.Format("Exception in AspNetCacheStorageProvider.Remove({0})", key), ex);
            }
        }

        public StorageEntry Get(string key)
        {
            try
            {
                return HttpRuntime.Cache.Get(key) as StorageEntry;
            }
            catch (Exception ex)
            {
                throw new StorageException(string.Format("Exception in AspNetCacheStorageProvider.Get({0})", key), ex);
            }

        }
        
        #endregion

    }
}
